import { useState, useCallback, useEffect } from 'react';

const useMediaQuery = (queries = [], values = [], defaultValue) => {
  const mediaQueryList = queries.map((q) => window.matchMedia(q));

  const getValue = useCallback(() => {
    const index = mediaQueryList.findIndex((mql) => mql.matches);
    return typeof values[index] !== 'undefined' ? values[index] : defaultValue;
  }, [mediaQueryList, values, defaultValue]);

  const [value, setValue] = useState(getValue);

  useEffect(() => {
    const handler = () => setValue(getValue);
    mediaQueryList.forEach((mql) => mql.addEventListener('change', handler));

    return () =>
      mediaQueryList.forEach((mql) =>
        mql.removeEventListener('change', handler)
      );
  }, [getValue, mediaQueryList]);

  return value;
};

export default useMediaQuery;

// 案例
// import { useMediaQuery } from './hooks';

// function App() {
//   const canHover = useMediaQuery(
//     // Media queries
//     ['(hover: hover)'],
//     // Values corresponding to the above media queries by array index
//     [true],
//     // Default value
//     false
//   );

//   const canHoverClass = 'opacity-0 hover:opacity-100 transition-opacity';
//   const defaultClass = 'opacity-100';

//   return (
//     <div className={canHover ? canHoverClass : defaultClass}>Hover me!</div>
//   );
// }

// export default App;
